using System;
using System.Text;
using System.Web;
using System.Web.UI;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Administration;

namespace CKS.InternetExtranet
{
    public class UserProfileRedirectControl : UserControl, IFormDelegateControlSource
    {        
        public void OnFormInit(object objOfInterest)
        {
            SPListItem user = objOfInterest as SPListItem;
            if (user != null)
            {
                this.RedirectIfNecessary(user);
            }
        }

        public void OnFormSave(object objOfInterest)
        {
        }

        private void RedirectIfNecessary(SPListItem user)
        {
            string name = user["Name"] as string;
            if (!string.IsNullOrEmpty(name))
            {
                SPWeb web = SPContext.Current.Web;

                try
                {
                    if (CustomMySettingsPageEnabled(web.Site))
                    {
                        string url = web.Url + "/_layouts/iee/userdisplay.aspx?" + Request.ServerVariables["QUERY_STRING"];
                        Response.Redirect(url, true);
                    }
                }
                catch (Exception ex)
                {
                    Utils.LogError(ex, true);
                }
            }            
        }

        private bool CustomMySettingsPageEnabled(SPSite site)
        {
            try
            {
                foreach (SPFeature feature in site.Features)
                {
                    SPFeatureDefinition definition = feature.Definition;
                    if (definition != null && definition.DisplayName == "UserProfileCustomPage")
                    {
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.LogError(ex);
            }

            return false;
        }
    }
}
